package com.inspectortime.webapp;

import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.validation.BindException;
import org.springframework.validation.ValidationUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

import com.inspectortime.domain.InspectorCompany;
import com.inspectortime.service.search.InspectorSearchService;
import com.inspectortime.webapp.util.HttpSessionUtils;

/**
 * Searches for Inspector Companies by a single search criteria
 * 
 * @author bones
 *
 */
public class SearchInspectorsController extends SimpleFormController {
	
	private InspectorSearchService searchService;
	
	protected Object formBackingObject(HttpServletRequest request)
		throws Exception {
		return new SearchInspectorsForm();
	}

	protected ModelAndView onSubmit(HttpServletRequest request,	HttpServletResponse response, Object command, BindException errors)
		throws Exception {

		SearchInspectorsForm form = (SearchInspectorsForm) command;
		ValidationUtils.rejectIfEmpty(errors, "searchTerm", "required");
		if (errors.getErrorCount() > 0) {
			return new ModelAndView(getFormView(), errors.getModel());
		}
		
		Set<InspectorCompany> results = this.searchService.searchForInspectorCompany(form.getSearchTerm());
		
		//Let's clear the session to remove any leftover inspection data 
		//in case a user is starting over from a previous wizard
		HttpSessionUtils.clearWizardInspection(request);
		
		ModelAndView mv = new ModelAndView(getSuccessView(), errors.getModel());
		mv.addObject("results", results);
		return mv;
		
	}

	public InspectorSearchService getSearchService() {
		return searchService;
	}

	public void setSearchService(InspectorSearchService searchService) {
		this.searchService = searchService;
	}
	

}
